package com.wzx.user.utils.quartzUtils;

/**
 * @author wzx
 * @version 1.0
 * @date 2023/5/17 - 17:10
 * @description 标题
 */
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

/**
 * @Description 定时任务调度工具类
 */
@Configuration
public class QuartzSchedulerUtil {
    // 任务调度
    @Autowired
    private Scheduler scheduler;


    /**
     * @Description: 开始执行所有任务
     * @Param []
     * @Return: void
     **/
    public void startAllJob() throws SchedulerException {
        TestJob1 testJob1 = new TestJob1();
        testJob1.startJob1(scheduler);
        scheduler.start();
    }


    /**
     * @Description: 获取Job信息
     * @Param [triggerName：触发器名, triggerGroupName：触发器组名]
     * @Return: java.lang.String
     **/
    public HashMap<Object, Object> getJobInfo(String triggerName, String triggerGroupName) throws SchedulerException {
        TriggerKey key = new TriggerKey(triggerName, triggerGroupName);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(key);
        String cronExpression = cronTrigger.getCronExpression();
        TimeZone timeZone = cronTrigger.getTimeZone();
        String description = cronTrigger.getDescription();
        JobKey jobKey = cronTrigger.getJobKey();
        TriggerKey triggerKey = cronTrigger.getKey();
        String state = scheduler.getTriggerState(triggerKey).name();

        HashMap<Object, Object> map = new HashMap<>();
        map.put("corn表达式", cronExpression);
        map.put("状态", state);
        map.put("时区", timeZone);
        map.put("任务描述", description);
        map.put("jobKey", jobKey);
        map.put("triggerKey", triggerKey);
        return map;
    }

    /**
     * @Description: 修改某个任务的执行时间
     * @Param [triggerName：触发器名, triggerGroupName：触发器组名, cornTime：corn表达式]
     * @Return: boolean
     **/
    public boolean modifyJob(String triggerName, String triggerGroupName, String cornTime) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
        CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(cornTime)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cornTime);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, triggerGroupName)
                    .withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }

    /**
     * @Description: 暂停所有任务
     * @Param []
     * @Return: void
     **/
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * @Description: 暂停某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    public void pauseJob(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.pauseJob(jobKey);
    }

    /**
     * @Description: 恢复所有任务
     * @Param []
     * @Return: void
     **/
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * @Description: 恢复某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    public void resumeJob(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.resumeJob(jobKey);
    }

    /**
     * @Description: 删除某个任务
     * @Param [jobName 任务名, jobGroupName 任务组名]
     * @Return: void
     **/
    public void deleteJob(String jobName, String jobGroupName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, jobGroupName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null)
            return;
        scheduler.deleteJob(jobKey);
    }

    /**
     * @Description: 创建某个定时任务并执行
     * @Param [
     * jobName 任务名,
     * jobGroupName 任务组名,
     * triggerName 触发器名,
     * triggerGroupName 触发器组名,
     * jobClass 任务类名,
     * cornTime corn表达式时间设置,
     * jobDescription 任务描述
     * ]
     * @Return: void
     **/
    public void addStartJob(QuartzJob quartzJob) throws SchedulerException, ClassNotFoundException {
        String jobName = quartzJob.getJobName();
        String jobGroupName = quartzJob.getJobGroupName();
        String triggerName = quartzJob.getTriggerName();
        String triggerGroupName = quartzJob.getTriggerGroupName();
        String jobClass = quartzJob.getJobClass();
        String cornTime = quartzJob.getCornTime();
        String jobDescription = quartzJob.getJobDescription();
        //判断是否已经有这个任务
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, triggerGroupName);
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        Class aClass = Class.forName(jobClass);
        //通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        //JobDetail 是具体Job实例
        if (null == trigger) {
            JobDetail jobDetail = JobBuilder.newJob(aClass)
                    .withIdentity(jobName, jobGroupName)
                    .build();
            //基于表达式构建触发器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cornTime);
            //CronTrigger表达式触发器 继承于Trigger
            //TriggerBuilder 用于构建触发器实例
            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, triggerGroupName)
                    .withDescription(jobDescription)
                    .withSchedule(cronScheduleBuilder)
                    .build();
            //开始执行
            scheduler.scheduleJob(jobDetail, cronTrigger);
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } else {
            //Trigger已存在，那么更新相应的定时设置
            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cornTime);
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withSchedule(scheduleBuilder)
                    .build();
            //按新的trigger重新设置job执行
            scheduler.rescheduleJob(triggerKey, trigger);
        }
    }
}
